package com.vip.jwt.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.vip.jwt.common.entity.R;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.*;
import com.vip.jwt.common.utils.app.APPWXAuthUtil;
import com.vip.jwt.common.utils.app.APPWXPayUtil;
import com.vip.jwt.common.utils.app.APPZFBPayUtil;
import com.vip.jwt.common.utils.sign.WXSignUtil;
import com.vip.jwt.common.utils.sign.ZFBSignUtil;
import com.vip.jwt.common.utils.xcx.wx.*;
import com.vip.jwt.entity.LoggerOnline;
import com.vip.jwt.entity.LoggerOperation;
import com.vip.jwt.entity.User;
import com.vip.jwt.entity.dto.UserDTO;
import com.vip.jwt.service.LoggerOnlineService;
import com.vip.jwt.service.UserService;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController extends BaseController{

    @Resource
    private UserService userService;

    @Resource
    private LoggerOnlineService loggerOnlineService;

    /**
     * 获取验证码
     * @return
     */
    @GetMapping("/images/captcha")
    public Object captcha(){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String verCode = specCaptcha.text();
        String verKey = RandomUtil.randomString(10);
        RedisUtil.set(verKey,verCode);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("ver_key",verKey);
        map.put("ver_code",specCaptcha.toBase64());
        return R.ok().data(map);
    }

    /**
     * 注册
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Object register(HttpServletRequest request,@RequestBody @Valid User user){
        String username = user.getUsername();
        String password = user.getPassword();
        User findUser = userService.findByUsername(username);
        boolean aNull = ObjectUtil.isNull(findUser);
        if(aNull){
            throw new MyException("账户不存在");
        }
        String salt = findUser.getSalt();
        String md5Password = User.encryptPassword(password,salt);
        String token = JwtUtil.sign(username,md5Password);
        JwtUtil.set(request,username,token);
        user.setPassword(md5Password);
        user.setSalt(salt);
        userService.save(user);
        return R.ok();
    }

    /**
     * 登录
     * @param request
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Object login(HttpServletRequest request, @RequestBody @Valid UserDTO userDTO){
        String verKey = userDTO.getVerKey();
        String verCode = userDTO.getVerCode().toLowerCase();
        String findVerCode = RedisUtil.get(verKey).toLowerCase();
        boolean bo = verCode.equals(findVerCode);
        if(!bo){
            throw new MyException("验证码不正确");
        }
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        User findUser = userService.findByUsername(username);
        boolean aNull = ObjectUtil.isNull(findUser);
        if(aNull){
            throw new MyException("账户不存在");
        }
        String salt = findUser.getSalt();
        String findPassword = findUser.getPassword();
        String md5Password = User.encryptPassword(password,salt);
        boolean equals = StrUtil.equals(findPassword, md5Password);
        if(!equals){
            throw new MyException("密码错误");
        }
        //登录日志
        LoggerOnline loggerOnline = new LoggerOnline();
        loggerOnline.setUsername(username);
        loggerOnlineService.saveLoginLogger(loggerOnline);
        //这里存入Redis中的password是加密之后的
        String token = JwtUtil.sign(username,md5Password);
        JwtUtil.set(request,username,token);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("id",findUser.getId());
        map.put("username",username);
        map.put("user",findUser);
        map.put("token",token);
        return R.ok().data(map);
    }

    /**
     * 修改密码
     * @return
     */
    @ApiOperation("修改密码")
    @PutMapping("/modify")
    public Object modify(@RequestParam("oldPassword") String oldPassword,@RequestParam("newPassword") String newPassword){
        User user = getUser();
        String md5Hash = User.encryptPassword(oldPassword,user.getSalt());
        if(md5Hash.equals(user.getPassword())){
            String salt = RandomUtil.randomString(5);
            md5Hash = User.encryptPassword(newPassword,salt);
            user.setSalt(salt);
            user.setPassword(md5Hash);
            userService.updateById(user);
            return R.ok();
        }else{
            return R.error().message("密码不正确");
        }
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Object logout(HttpServletRequest request){
        String username = getUsername();
        JwtUtil.delete(request,username);
        //登出日志
        LoggerOnline loggerOnline = new LoggerOnline();
        loggerOnline.setUsername(getUsername());
        loggerOnlineService.saveLogoutLogger(loggerOnline);
        return R.ok();
    }

}

